import {Component, ViewContainerRef, ComponentResolver, ViewChild} from '@angular/core';

import _ from 'lodash';

import {Test1} from './test1';

@Component({
  selector: 'ft-tabs',
  inputs: ['tabs'],
  queries: {
    head: new ViewChild('head'),
    content: new ViewChild('content', { read: ViewContainerRef }),
  },
  template: `
  <div class="ft-tabs">
    <div #head class="ft-tabs-head">
      <a *ngFor="let item of tabs" (click)="select(item)" [class.selected]="item == selected">
        {{item.name}}
      </a>
    </div>
    <div #content class="ft-tabs-content"></div>
  </div>`
})
export class FtTabs {

  static get parameters() {
    return [[ComponentResolver]];
  }

  constructor(resolver) {
    this.resolver = resolver;
  }

  // ngOnInit() {
  //   console.log('ngOnInit');
  //   console.log(this.tabs);
  // }

  // ngAfterViewInit() {
  //   console.log('ngAfterViewInit');
  //   console.log(this.tabs);
  // }

  ngOnChanges() {
    console.log('ngOnChanges');
    console.log(this.tabs);
    this.selected = _.head(this.tabs);
  }

  select(item) {
    console.log(item);
    console.log(this.tabs);
    this.selected = item;

    if (this.cmpRef) {
      this.cmpRef.destroy();
    }

    this.resolver.resolveComponent(Test1).then(factory => {
      console.log(factory);
      console.log(this.target);
      this.cmpRef = this.content.createComponent(factory);
    });
  }

  // updateComponent() {
  //   if (!this.isViewInitialized) {
  //     return;
  //   }
  //   if (this.cmpRef) {
  //     this.cmpRef.destroy();
  //   }
  //   //    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
  //   this.resolver.resolveComponent(this.type).then((factory: ComponentFactory<any>) => {
  //     this.cmpRef = this.target.createComponent(factory)
  //   });
  // }

  // ngOnChanges() {
  //   this.updateComponent();
  // }

  // ngAfterViewInit() {
  //   this.isViewInitialized = true;
  //   this.updateComponent();
  // }

  // ngOnDestroy() {
  //   if (this.cmpRef) {
  //     this.cmpRef.destroy();
  //   }
  // }
}